<?php

namespace app\index\controller;
use think\admin\Controller;
use app\api\model\SystemOplog;

class Order extends Controller
{
    /**
     * 图书  文具支付完成通知
     * @return void
     */
    public function mallnotify(){
        $postStr = file_get_contents("php://input");
         sysoplog('订单通知',$postStr);
        $xml = \Tools::xmlToArray($postStr);
//        $una_code = substr($xml['r'], strrpos($xml['r'], '/')+1);
//        $xml = json_decode('{"appid":"wx1a36e3d7aa689cb9","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1489519502","nonce_str":"fT2tA7zG7nK4ae5SraXf","openid":"o84Ym0dcWVewgCsaxxk3XmTx3dGU","out_trade_no":"1201905291404","result_code":"SUCCESS","return_code":"SUCCESS","sign":"5CC983BB0D09D3AA0938A281CD2EC359","time_end":"20180116121318","total_fee":"19900","trade_type":"JSAPI","transaction_id":"4200000051201801164489757035"}
//',true);
        if (isset($xml['return_code']) && $xml['return_code'] == 'SUCCESS') {
            $orderModel = new \app\api\model\ShopOrder();
            $orderDetailModel = new \app\api\model\ShopOrderDetail();
            $orderModel->startTrans();
            $tmporder = explode('_', $xml['out_trade_no']);
            $order_no = count($tmporder) == 2 ? $tmporder[0] : $xml['out_trade_no'];
            $order_info = $orderModel->getOne(array(
                 'order_no'  => $order_no
            ));
            $data = [];
            if(empty($order_info) === FALSE){
                if(intval($order_info['payment_amount']) == intval($xml['total_fee'])){
                    if($order_info['status'] == 2){
                        $data['payment_trade']     = $xml['transaction_id'];
                        $data['openid']     = $xml['openid'];
                        $data['payment_status']     = 1;
                        $data['payment_datetime']       = \Tools::getDateTimeByTime();
                        $data['update_at']       = \Tools::getDateTimeByTime();
                        $data['status']         = 4;
                        $data['payment_remark']        = json_encode($xml);
                        //处理后续工作
                        $opera = [];
                        //修改订单状态
                        $opera[] = $orderModel->saveData(array(
                            'order_no'  => $order_no
                        ),$data);
                        //删除购物车中选择状态

                        $shopCartModel = new \app\api\model\ShopCart();
                        $cart_info = $shopCartModel->getOne(array(
                            'user_id'   =>$order_info['uuid'],
                            'select'    =>1
                        ));
                        if(empty($cart_info) === FALSE) {
                            $opera[] = $shopCartModel->delData(array(
                                'user_id' => $order_info['uuid'],
                                'select' => 1
                            ));
                        }
                        //TODO 更新用户积分
                        //TODO 消费优惠券
                        //TODO 记日志
                        if($order_info['payment_balance'] > 0){
                            //更新佣金
                            $userAccountModel = new \app\api\model\DataUserAccount();
                            $opera[] = $userAccountModel->decNum(array(
                                'uuid'  => $order_info['uuid']
                            ),'avail_amount',$order_info['payment_balance']);
                            $opera[] = $userAccountModel->decNum(array(
                                'uuid'  => $order_info['uuid']
                            ),'freeze_amount',$order_info['payment_balance']);
                            $opera[] = $userAccountModel->incNum(array(
                                'uuid'  => $order_info['uuid']
                            ),'used_amount',$order_info['payment_balance']);
                            //添加佣金记录
                            $commissionModel = new \app\api\model\DataUserCommission();
                            $opera[] = $commissionModel->addData(array(
                                'uuid'          => $order_info['uuid'],
                                'order_no'      => $order_info['order_no'],
                                'type'          => 1,
                                'used_order_no' => $order_info['order_no'],
                                'created_at'    =>\Tools::getDateTimeByTime(),
                                'amount'        => $order_info['payment_amount'],
                                'commission_amount'=> $order_info['payment_balance'],
                                'product_uuid'  => 0,
                                'product_level' => 0,
                                'product_rate'  => 0
                            ));
                        }
                        //更改库存
                        $orderDetail = $orderDetailModel->getLists(array(
                            'order_no'  => $order_no
                        ),'goods_sku,product_id,goods_code,stock_sales,goods_name');
                        $goodsModel = new \app\api\model\ShopGoods();
                        $goodsDetailModel = new \app\api\model\ShopGoodsItem();
                        if(empty($orderDetail) === FALSE){
                            foreach($orderDetail as &$dv){
                                $opera[] = $goodsDetailModel->decNum(array(
                                    'goods_sku' => $dv['goods_sku']
                                ),'freeze_stock',$dv['stock_sales']);
                                $opera[] = $goodsDetailModel->incNum(array(
                                    'goods_sku' => $dv['goods_sku']
                                ),'stock_sales',$dv['stock_sales']);
                                //更新主商品库存
                                $opera[] = $goodsModel->decNum(array(
                                    'code' => $dv['goods_code']
                                ),'freeze_stock',$dv['stock_sales']);
                                $opera[] = $goodsModel->incNum(array(
                                   'code' => $dv['goods_code']
                                ),'stock_sales',$dv['stock_sales']);
                            }
                        }
                        //计算佣金分配
                        //绑定分销层级
                        if(empty($order_info['order_detail']) === FALSE){
                            $orderDetail = json_decode($order_info['order_detail'],true);
                            //获取当前用户的上级分销员信息
                            $userModel = new \app\api\model\DataUser();
                            $userInfo = $userModel->getOne(array(
                                'id'    => $order_info['uuid']
                            ),'pre_dis_id,pre_pre_dis_id,dis_path,id');
                            $updateData = [];
                            $can_commission = 1;
                            if($userInfo['pre_dis_id'] == 0){
                                //不存在上级  则绑定上级
                                if(isset($orderDetail['share_user_code']) && empty($orderDetail['share_user_code']) === FALSE){
                                    $pre_disinfo = $userModel->getOne(array(
                                        'distribution_code' => $orderDetail['share_user_code']
                                    ),'pre_dis_id,dis_path,id');
                                    if(empty($pre_disinfo) === FALSE){//用户存在
                                        $updateData['pre_dis_id'] = $pre_disinfo['id'];
                                        $updateData['pre_pre_dis_id'] = $pre_disinfo['pre_dis_id'];
                                        $updateData['dis_path'] = $pre_disinfo['dis_path'].$order_info['uuid'].'#*#';
                                        $updateData['update_at'] = \Tools::getDateTimeByTime();
                                        $opera[] = $userModel->saveData(array(
                                            'id'    => $order_info['uuid']
                                        ),$updateData);
                                        $pre_id = $pre_disinfo['id'];
                                        $pre_pre_dis_id = $pre_disinfo['pre_dis_id'];
                                    }else{
                                        $can_commission = 0;
                                    }
                                }else{
                                    $can_commission = 0;
                                }
                            }else{
                                $pre_id = $userInfo['pre_dis_id'];
                                $pre_pre_dis_id = $userInfo['pre_pre_dis_id'];
                            }
                            if($can_commission == 1) {
                                //处理分佣
//                                $opera = $this->handleCommission($pre_id, $pre_pre_dis_id,$order_info,$opera);
                            }
                        }
                        if(\Tools::checkArrayResult($opera)){
                            $orderModel->commit();
                            echo 'success';
                        }else{
                            $orderModel->rollback();

                            echo 'error';
                        }
                    } else {
                        echo 'success';
                    }
                }else{
                    sysoplog('订单支付失败通知','fail1订单号：'.$order_no."金额不正确");
                }
            }else{
                sysoplog('订单支付失败通知','fail2订单号：'.$order_no."不正确");
            }
        } else {
            sysoplog('订单支付失败通知','异常通知，内容fail3：'.json_encode($xml));
        }
    }

    /**
     * 计算佣金
     * @param $pre_id
     * @param $pre_pre_id
     * @param $orderinfo
     * @param $opera
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function handleCommission($pre_id = 0,$pre_pre_id = 0,$orderinfo = [],$opera=[]){
        $amount = $orderinfo['payment_amount'] - $orderinfo['amount_express'];//产生分佣的金额为抛去运费的
        $userModel = new \app\api\model\DataUserAccount();
        $commissionModel = new \app\api\model\DataUserCommission();
        //获取分佣比例
        $pre_rate = sysconf('pre_rate');
        $pre_pre_rate = sysconf('pre_pre_rate');
        if(empty($pre_rate)) $pre_rate = 10;
        if(empty($pre_pre_rate)) $pre_rate = 10;
        $distributionModel = new \app\api\model\DataUserDistribution();
        if(empty($pre_rate) === FALSE && $pre_rate > 0){
            if($pre_id > 0){
                //获取当前用户的佣金占比
                $distributioninfo = $distributionModel->getOne(array(
                    'uuid'  => $pre_id,
                    'status'    =>1
                ));
                if(empty($distributioninfo) === FALSE) {
                    $pre_rate = $distributioninfo['first_rate'];
                    $pre_amount = $amount * $pre_rate;
                    $opera[] = $userModel->incNum(array(
                        'uuid' => $pre_id
                    ), 'all_amount', $pre_amount);
                    $opera[] = $userModel->incNum(array(
                        'uuid' => $pre_id
                    ), 'wait_amount', $pre_amount);
                    //添加佣金记录
                    $opera[] = $commissionModel->addData(array(
                        'uuid' => $pre_id,
                        'order_no' => $orderinfo['order_no'],
                        'type' => 0,
                        'created_at' => \Tools::getDateTimeByTime(),
                        'amount' => $amount,
                        'commission_amount' => $pre_amount,
                        'product_uuid' => $orderinfo['uuid'],
                        'product_level' => 0,
                        'product_rate' => $pre_rate
                    ));
                }
            }
        }
        if(empty($pre_pre_rate) === FALSE && $pre_pre_rate > 0){
            if($pre_pre_id > 0){
                 //获取当前用户的佣金占比
                $distributioninfo = $distributionModel->getOne(array(
                    'uuid'  => $pre_pre_id,
                    'status'    =>1
                ));
                if(empty($distributioninfo) === FALSE) {
                    $pre_pre_rate = $distributioninfo['second_rate'];
                    $pre_pre_amount = $amount * $pre_pre_rate;
                    $opera[] = $userModel->incNum(array(
                        'uuid' => $pre_pre_id
                    ), 'all_amount', $pre_pre_amount);
                    $opera[] = $userModel->incNum(array(
                        'uuid' => $pre_pre_id
                    ), 'wait_amount', $pre_pre_amount);

                    //添加佣金记录
                    $opera[] = $commissionModel->addData(array(
                        'uuid' => $pre_id,
                        'order_no' => $orderinfo['order_no'],
                        'type' => 0,
                        'created_at' => \Tools::getDateTimeByTime(),
                        'amount' => $amount,
                        'commission_amount' => $pre_pre_amount,
                        'product_uuid' => $orderinfo['uuid'],
                        'product_level' => 1,
                        'product_rate' => $pre_pre_rate
                    ));
                }
            }
        }
        return $opera;
    }
    /**
     * 支付会员通知
     * @return void
     */
    public function vipnotify(){
        $postStr = file_get_contents("php://input");
        sysoplog('订单通知',$postStr);
        $debug = input('debug', 0);
        $xml = \Tools::xmlToArray($postStr);
        if (isset($xml['return_code']) && $xml['return_code'] == 'SUCCESS') {
            $orderModel = new \app\api\model\ShopOrder();
            $tmporder = explode('_', $xml['out_trade_no']);
            $order_no = count($tmporder) == 2 ? $tmporder[0] : $xml['out_trade_no'];
            $order_info = $orderModel->getOne(array(
                 'order_no'  => $order_no
            ));
            $data = [];
            if (empty($order_info) === false) {
                if (intval($order_info['payment_amount']) == intval($xml['total_fee'])) {
                    if ($order_info['status'] == 2) {
                        $data['payment_status']     = 1;
                        $data['payment_trade']     = $xml['transaction_id'];
                        $data['openid']     = $xml['openid'];
                        $data['payment_datetime']       = \Tools::getDateTimeByTime();
                        $data['update_at']       = \Tools::getDateTimeByTime();
                        $data['status']         = 4;
                        $data['payment_remark']        = json_encode($xml);

                        //处理后续工作
                        $opera = [];
                        $orderModel->startTrans();
                        $opera[] = $orderModel->saveData([
                            'order_no' => $order_no,
                        ], $data);
                        //余额修改记录结束
                        //修改用户状态
                        $userModel = new \app\api\model\DataUser();
                        $user = $userModel->getOne(array(
                            'id'    => $order_info['uuid']
                        ),'is_vip,vip_expire,vip_datetime,username');
                        $resdata = array(
                            'is_vip'    =>1,
                            'update_at' =>\Tools::getDateTimeByTime()
                        );
                        if($user['is_vip'] == 0){
                            $resdata['vip_expire'] = \Tools::getDateTimeByTime(strtotime("+1 year"));
                            $resdata['vip_datetime'] = \Tools::getDateTimeByTime();
                        }else{
                            $resdata['vip_expire'] = \Tools::getDateTimeByTime(strtotime($user['vip_expire']),strtotime("+1 year"));
                        }
                        $opera[] = $userModel->saveData(array(
                            'id'    => $order_info['uuid']
                        ),$resdata);
                        if (\Tools::checkArrayResult($opera)) {
                            $orderModel->commit();
                            echo 'success';
                        } else {
                            $orderModel->rollback();
                            echo 'fail';
                            sysoplog('订单支付失败通知','订单号：' . $order_no . "支付失败");
                        }
                    } else {
                        echo 'success';
                    }
                } else {
                    echo 'fail1';
                    sysoplog('订单支付失败通知','fail1订单号：'.$order_no."金额不正确");
                }
            } else {
                echo 'fail2';
                sysoplog('订单支付失败通知','fail1订单号：'.$order_no."不正确");
            }
        } else {
            echo 'fail3';
            sysoplog('订单支付失败通知','异常通知，内容fail3：'.json_encode($xml));
        }
    }
}
